﻿// Sterren beoordeel systeem
$(function stars() {
    $("#rat").children().not("select, #rating_title").hide();

    // Create caption element
    var $caption = $('<div id="caption"/>');

    // Create stars
    $("#rat").stars({
        inputType: "select",
        oneVoteOnly: true,
        captionEl: $caption,
        callback: function (ui, type, value) {
            // Display message to the user at the begining of request
            $("#messages").text("Saving...").fadeIn(30);

            var mediaObjectId = $("#mediaObjectId").val();

            // Send request to the server using POST method
            /* NOTE: 
            The same PHP script is used for the FORM submission when Javascript is not available.
            The only difference in script execution is the returned value. 
            For AJAX call we expect an JSON object to be returned. 
            The JSON object contains additional data we can use to update other elements on the page.
            To distinguish the AJAX request in PHP script, check if the $_SERVER['HTTP_X_REQUESTED_WITH'] header variable is set.
            (see: demo4.php)
            */

            $.post("/Rating", { rate: value, mediaObjectId: mediaObjectId }, function (json) {
                // Change widget's title
                $("#rating_title").text("Gemiddeld: ");

                // Select stars from "Average rating" control to match the returned average rating value
                ui.select(Math.round(json.avg));

                // Update widget's caption
                $caption.text(" (" + json.votes + " stemmen)");

                // Display confirmation message to the user
                var opties = ["1 Ster", "2 Sterren", "3 Sterren", "4 Sterren", "5 Sterren"];

                $("#messages").text("(" + opties[value - 1] + ") opgeslagen.").stop().css("opacity", 1).fadeIn(30);

                // Hide confirmation message after 2 sec...
                setTimeout(function () {
                    $("#messages").fadeOut(1000)
                }, 2000);

            }, "json");
        }
    });

    // Since the <option value="3"> was selected by default, we must remove this selection from Stars.
    //$("#rat").stars("selectID", -1);

    // Append caption element !after! the Stars
    $caption.appendTo("#rat");

    // Create element to use for confirmation messages
    $('<div id="messages"/>').appendTo("#rat");
});